package vn.ikame.android.truyenf17;

import java.io.IOException;

import vn.ikame.android.adapter.ListChapAdapter;
import vn.ikame.android.handler.CHandler;
import vn.ikame.android.utils.CommonUtils;
import vn.ikame.android.utils.XMLParser;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;

public class ChapList extends Activity {
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	
	ListView list;
	ListChapAdapter arrayAdapter;
	private AdView adView;
	
	//download
	private AlertDialog.Builder alert;
	private ProgressDialog mProgressDialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chaplist);
		
		LinearLayout lLinLayout = (LinearLayout) findViewById(R.id.layoutchaplist);
	    
	    RelativeLayout.LayoutParams adParams2 = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		adParams2.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		adParams2.addRule(RelativeLayout.CENTER_IN_PARENT);
		
		
		adView = new AdView(this, AdSize.SMART_BANNER, "a1502465d6a93ed");
		adView.loadAd(new AdRequest());

		lLinLayout.addView(adView, adParams2);

		
		if(CommonUtils.isNetworkConnected(this)){
			initChapList();
        } else {
        	alert = new AlertDialog.Builder(this);
        	alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
    		alert.setPositiveButton("Thử lại",
    				new DialogInterface.OnClickListener() {
    					public void onClick(DialogInterface dialog,
    							int whichButton) {
    						initChapList();
    					}
    				});
    		alert.setNegativeButton("Thoát",
    				new DialogInterface.OnClickListener() {
    					public void onClick(DialogInterface dialog,
    							int whichButton) {
    						ChapList.this.finish();
    						System.gc();
    						android.os.Process.killProcess(android.os.Process.myPid());
    					}
    				});
    		
    		alert.setCancelable(true);
    		alert.show();
        }
		
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.layout.menu, menu);
	    return true;
	}
	
	public void createAboutMessage(){
		alert = new AlertDialog.Builder(this);
		alert.setMessage(R.string.about);
		alert.setPositiveButton("Gửi mail",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
						final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);

						/* Fill it with Data */
						emailIntent.setType("plain/text");
						emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"support@ikame.vn"});
						emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Ứng dụng truyện ngắn - f145");
						emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Nội dung: ");

						/* Send it off to the Activity-Chooser */
						startActivity(Intent.createChooser(emailIntent, "Send mail..."));
					}
				});

		alert.setNegativeButton("Đóng",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
					}
				});
		alert.setCancelable(false);
		alert.show();
    }
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.gotomark:
			if(CHandler.store.getStoryID() > 0){
				
				CHandler.storyName = CHandler.store.getStoryName();
				CHandler.chapID = CHandler.store.getChapID();
				CHandler.storyID = CHandler.store.getStoryID();
				CHandler.chapPos = CHandler.store.getChapPos();
				initChapList2();
//				try{
//					CHandler.isReadMarkChap = true;
//					CHandler.chapName = CHandler.chapList.get(CHandler.chapPos).getChapName();
//					CHandler.chapID = CHandler.chapList.get(CHandler.chapPos).getId();
//					this.finish();
//					startActivity(new Intent(ChapList.this, Content.class));
//				}catch (Exception e) {
//					// TODO: handle exception
//				}
				
			} else {
				Toast.makeText(this, "Chưa có chap nào được đánh dấu", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.refresh:
			if(CommonUtils.isNetworkConnected(this)){
	        	initChapList();
	        } else {
	        	alert = new AlertDialog.Builder(this);
	        	alert.setMessage("Vui lòng kiểm tra lại kết nối mạng");
	    		alert.setPositiveButton("Thử lại",
	    				new DialogInterface.OnClickListener() {
	    					public void onClick(DialogInterface dialog,
	    							int whichButton) {
	    						initChapList();
	    					}
	    				});
	    		alert.setNegativeButton("Thoát",
	    				new DialogInterface.OnClickListener() {
	    					public void onClick(DialogInterface dialog,
	    							int whichButton) {
	    						ChapList.this.finish();
	    						System.gc();
	    						android.os.Process.killProcess(android.os.Process.myPid());
	    					}
	    				});
	    		
	    		alert.setCancelable(true);
	    		alert.show();
	        }
			break;
		case R.id.about:
			createAboutMessage();
			break;

		}
		return true;
	}
	
	
	public void initChapList(){
		try {
			//Tạo task kết nối với server
			new AsyncTask<Void, Void, String>() {
				@Override
				protected void onPreExecute() {
					//Hiển thị thông báo
					showDialog(DIALOG_DOWNLOAD_PROGRESS);
				}

				@Override
				protected String doInBackground(Void... arg0) {
					try {
						
						Thread theard = new Thread() {
							@Override
							public void run() {
								try {
									
									int waited = 0;
									while (true && (waited < 10000)) {
										sleep(100);
										if (true) {
											waited += 100;
										}
									}
									
								} catch (Exception e) {
									// do nothing
								} finally{
									try{
										System.out.println("Không kết nối được đến server");
										dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
									}catch (Exception e) {
										// TODO: handle exception
									}
								}
							}
						};
						theard.start();
						
						CHandler.chapList = XMLParser.getChapList("http://data.ikame.vn/f17/index.php?cateid=" + CHandler.storyID);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 22");
						try{
							StoryList.detailsTracker.trackPageView("Connection error - ChapList");
							StoryList.detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 33");
						try{
							StoryList.detailsTracker.trackPageView("Connection error - ChapList");
							StoryList.detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}
					}
					return "";
				}
				//Hoàn thành truy vấn
				@Override
				protected void onPostExecute(String result) {
					
					try {
						arrayAdapter = new ListChapAdapter(ChapList.this, R.layout.listview_chap,
								CHandler.chapList);

						list = (ListView) findViewById(R.id.list_chap);
						list.setAdapter(arrayAdapter);

						list.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent, View view,
									int position, long id) {
								// TODO Auto-generated method stub
								
								CHandler.chapName = CHandler.chapList.get(position).getChapName();
								CHandler.chapID = CHandler.chapList.get(position).getId();
								CHandler.chapPos = position;
								CHandler.isReadMarkChap = false;
								startActivity(new Intent(ChapList.this, Content.class));
//								ChapList.this.finish();
							}

						});
					} catch (Exception e) {
					}
					try{
						dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
					}catch (Exception e) {
						// TODO: handle exception
					}
				}
			}.execute();
		} catch (Exception e) {
		}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
			startActivity(new Intent(ChapList.this, StoryList.class));
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Loading...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(true);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}
	
	public void initChapList2() {
		try {
			// Tạo task kết nối với server
			new AsyncTask<Void, Void, String>() {
				@Override
				protected void onPreExecute() {
					// Hiển thị thông báo
					showDialog(DIALOG_DOWNLOAD_PROGRESS);
				}

				@Override
				protected String doInBackground(Void... arg0) {
					try {

						Thread theard = new Thread() {
							@Override
							public void run() {
								try {

									int waited = 0;
									while (true && (waited < 10000)) {
										sleep(100);
										if (true) {
											waited += 100;
										}
									}

								} catch (Exception e) {
									// do nothing
								} finally {
									try {
										System.out
												.println("Không kết nối được đến server");
										dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
									} catch (Exception e) {
										// TODO: handle exception
									}
								}
							}
						};
						theard.start();

						CHandler.storyName = CHandler.store.getStoryName();
						CHandler.chapID = CHandler.store.getChapID();
						CHandler.storyID = CHandler.store.getStoryID();
						CHandler.chapPos = CHandler.store.getChapPos();
						CHandler.chapList = XMLParser.getChapList("http://data.ikame.vn/f17/index.php?cateid=" + CHandler.storyID);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 22");
						try {
							StoryList.detailsTracker
									.trackPageView("Connection error - ChapList");
							StoryList.detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}

					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						System.out.println("Không kết nối được đến server 33");
						try {
							StoryList.detailsTracker
									.trackPageView("Connection error - ChapList");
							StoryList.detailsTracker.dispatch();
						} catch (Exception de) {
							// TODO: handle exception
						}
					}
					return "";
				}

				// Hoàn thành truy vấn
				@Override
				protected void onPostExecute(String result) {
					try {
						dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
					} catch (Exception e) {
						// TODO: handle exception
					}
//					CHandler.chapID = CHandler.store.getChapID();
//					CHandler.storyID = CHandler.store.getStoryID();
//					CHandler.chapPos = CHandler.store.getChapPos();

					try{
						
						CHandler.chapName = CHandler.chapList.get(CHandler.chapPos)
								.getChapName();
						CHandler.chapID = CHandler.chapList.get(CHandler.chapPos)
								.getId();

						System.out.println("   " + CHandler.chapName);
						try{
							CHandler.isReadMarkChap = true;
							CHandler.chapName = CHandler.chapList.get(CHandler.chapPos).getChapName();
							CHandler.chapID = CHandler.chapList.get(CHandler.chapPos).getId();
							ChapList.this.finish();
							startActivity(new Intent(ChapList.this, Content.class));
						}catch (Exception e) {
							// TODO: handle exception
						}
					}catch (Exception e) {
						// TODO: handle exception
					}

				}
			}.execute();
		} catch (Exception e) {
		}
	}
	
}
